package boot.spring.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import boot.spring.pagemodel.DataGrid;
import boot.spring.pagemodel.MSG;
import boot.spring.pagemodel.SignTask;
import boot.spring.po.Permission;
import boot.spring.po.Role;
import boot.spring.po.Role_permission;
import boot.spring.po.SignApply;
import boot.spring.po.User;
import boot.spring.po.User_role;
import boot.spring.service.SignService;
import boot.spring.service.SystemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "会签流程接口")
@Controller
public class SignController {
	@Autowired
	SignService signService;
	@Autowired
	SystemService systemservice;
	@Autowired
	TaskService taskservice;
	@Autowired
	RuntimeService runservice;
	
	@RequestMapping(value = "/signapply", method = RequestMethod.GET)
	public String sign() {
		return "sign/signapply";
	}
	@RequestMapping(value = "/deptmleaderaudit", method = RequestMethod.GET)
	public String mytask() {
		return "sign/deptmleaderaudit";
	}
	/**
	 * 跳转至财务管理员页面
	 * @return
	 */
	@RequestMapping(value = "/cwaudit", method = RequestMethod.GET)
	public String cw() {
		return "sign/cwaudit";
	}
	@RequestMapping(value = "/task/cwcomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public MSG cwcomplete(HttpSession session, @PathVariable("taskid") String taskid, HttpServletRequest req) {
		String userid = (String) session.getAttribute("username");
		Map<String, Object> variables = new HashMap<String, Object>();
		String approve = req.getParameter("hrapprove");
		variables.put("hrapprove", approve);
		// 获取流程实例
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid, variables);
		return new MSG("success");
	}
	/**
	 * 跳转至总经理审批页面
	 * @return
	 */
	@RequestMapping(value="/manageraudit",method=RequestMethod.GET)
	String manager(){
		return "sign/manageraudit";
	}
	@RequestMapping(value = "/startSign", method = RequestMethod.POST)
	@ResponseBody
	public MSG start_sign(SignApply apply, HttpSession session) {
		String userid = (String) session.getAttribute("username");
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("applyuserid", userid);
		List<String> assigneeList = new ArrayList<>();
		assigneeList.add("部门经理");
		assigneeList.add("财务管理员");
		assigneeList.add("总经理");
		variables.put("assigneeList", assigneeList);
		ProcessInstance ins = signService.startWorkflow(apply, userid, variables);
		System.out.println("流程id" + ins.getId() + "已启动");
		return new MSG("sucess");
	}
	/**
	 * 部门领导审批代办列表（会签）
	 * @param session
	 * @param current
	 * @param rowCount
	 * @return
	 */
	@ApiOperation("获取部门领导审批代办列表")
	@RequestMapping(value = "/signdepttasklist", produces = {
			"application/json;charset=UTF-8" }, method = RequestMethod.POST)
	@ResponseBody
	public DataGrid<SignTask> getdepttasklist(HttpSession session, @RequestParam("current") int current,
			@RequestParam("rowCount") int rowCount) {
		DataGrid<SignTask> grid = new DataGrid<SignTask>();
		grid.setRowCount(rowCount);
		grid.setCurrent(current);
		grid.setTotal(0);
		grid.setRows(new ArrayList<SignTask>());
		// 先做权限检查，对于没有部门领导审批权限的用户,直接返回空
		String userid = (String) session.getAttribute("username");
		int uid = systemservice.getUidByusername(userid);
		User user = systemservice.getUserByid(uid);
		List<User_role> userroles = user.getUser_roles();
		if (userroles == null)
			return grid;
		boolean flag = false;// 默认没有权限
		for (int k = 0; k < userroles.size(); k++) {
			User_role ur = userroles.get(k);
			Role r = ur.getRole();
			int roleid = r.getRid();
			Role role = systemservice.getRolebyid(roleid);
			List<Role_permission> p = role.getRole_permission();
			for (int j = 0; j < p.size(); j++) {
				Role_permission rp = p.get(j);
				Permission permission = rp.getPermission();
				if (permission.getPermissionname().equals("部门领导审批"))
					flag = true;
				else
					continue;
			}
		}
		if (flag == false)// 无权限
		{
			return grid;
		} else {
			int firstrow = (current - 1) * rowCount;
			List<SignApply> results = signService.getpagedepttask(userid, firstrow, rowCount);
			int totalsize = signService.getalldepttask(userid);
			List<SignTask> tasks = new ArrayList<SignTask>();
			for (SignApply apply : results) {
				SignTask task = new SignTask();
				task.setApply_time(apply.getApply_time());
				task.setUser_id(apply.getUser_id());
				task.setEnd_time(apply.getEnd_time());
				task.setId(apply.getId());
				task.setSign_type(apply.getSign_type());
				task.setProcess_instance_id(apply.getProcess_instance_id());
				task.setProcessdefid(apply.getTask().getProcessDefinitionId());
				task.setReason(apply.getReason());
				task.setStart_time(apply.getStart_time());
				task.setTaskcreatetime(apply.getTask().getCreateTime());
				task.setTaskid(apply.getTask().getId());
				task.setTaskname(apply.getTask().getName());
				tasks.add(task);
			}
			grid.setRowCount(rowCount);
			grid.setCurrent(current);
			grid.setTotal(totalsize);
			grid.setRows(tasks);
			return grid;
		}
	}
	/**
	 * 财务人员待处理列表
	 * @param session
	 * @param current
	 * @param rowCount
	 * @return
	 */
	@RequestMapping(value = "/cwtasklist", produces = { "application/json;charset=UTF-8" }, method = RequestMethod.POST)
	@ResponseBody
	public DataGrid<SignTask> getcwtasklist(HttpSession session, @RequestParam("current") int current,
			@RequestParam("rowCount") int rowCount) {
		DataGrid<SignTask> grid = new DataGrid<SignTask>();
		grid.setRowCount(rowCount);
		grid.setCurrent(current);
		grid.setTotal(0);
		grid.setRows(new ArrayList<SignTask>());
		// 先做权限检查，对于没有财务管理员权限的用户,直接返回空
		String userid = (String) session.getAttribute("username");
		int uid = systemservice.getUidByusername(userid);
		User user = systemservice.getUserByid(uid);
		List<User_role> userroles = user.getUser_roles();
		if (userroles == null)
			return grid;
		boolean flag = false;// 默认没有权限
		for (int k = 0; k < userroles.size(); k++) {
			User_role ur = userroles.get(k);
			Role r = ur.getRole();
			int roleid = r.getRid();
			Role role = systemservice.getRolebyid(roleid);
			List<Role_permission> p = role.getRole_permission();
			for (int j = 0; j < p.size(); j++) {
				Role_permission rp = p.get(j);
				Permission permission = rp.getPermission();
				if (permission.getPermissionname().equals("财务审批"))
					flag = true;
				else
					continue;
			}
		}
		if (flag == false)// 无权限
		{
			return grid;
		} else {
			int firstrow = (current - 1) * rowCount;
			List<SignApply> results = signService.getpagecwtask(userid, firstrow, rowCount);
			int totalsize = signService.getallcwtask(userid);
			List<SignTask> tasks = new ArrayList<SignTask>();
			for (SignApply apply : results) {
				SignTask task = new SignTask();
				task.setApply_time(apply.getApply_time());
				task.setUser_id(apply.getUser_id());
				task.setEnd_time(apply.getEnd_time());
				task.setId(apply.getId());
				task.setSign_type(apply.getSign_type());
				task.setProcess_instance_id(apply.getProcess_instance_id());
				task.setProcessdefid(apply.getTask().getProcessDefinitionId());
				task.setReason(apply.getReason());
				task.setStart_time(apply.getStart_time());
				task.setTaskcreatetime(apply.getTask().getCreateTime());
				task.setTaskid(apply.getTask().getId());
				task.setTaskname(apply.getTask().getName());
				tasks.add(task);
			}
			grid.setRowCount(rowCount);
			grid.setCurrent(current);
			grid.setTotal(totalsize);
			grid.setRows(tasks);
			return grid;
		}
	}
	@RequestMapping(value = "/dealcwtask", method = RequestMethod.POST)
	@ResponseBody
	public SignApply dealcwtask(@RequestParam("taskid") String taskid, HttpServletResponse response) {
		Task task = taskservice.createTaskQuery().taskId(taskid).singleResult();
		ProcessInstance process = runservice.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId())
				.singleResult();
		SignApply leave = signService.getleave(new Integer(process.getBusinessKey()));
		return leave;
	}
	/**
	 * 总经理待处理事件列表(会签)
	 * @param session
	 * @param current
	 * @param rowCount
	 * @return
	 */
	@RequestMapping(value="/mansigntasklist",method=RequestMethod.POST)
	@ResponseBody
	DataGrid<SignTask> mansigntasklist(HttpSession session,@RequestParam("current") int current,@RequestParam("rowCount") int rowCount){
		DataGrid<SignTask> grid = new DataGrid<SignTask>();
		grid.setRowCount(rowCount);
		grid.setCurrent(current);
		grid.setTotal(0);
		grid.setRows(new ArrayList<SignTask>());
		// 先做权限检查，对于没有财务管理员权限的用户,直接返回空
		String userid = (String) session.getAttribute("username");
		int uid = systemservice.getUidByusername(userid);
		User user = systemservice.getUserByid(uid);
		List<User_role> userroles = user.getUser_roles();
		if (userroles == null)
			return grid;
		boolean flag = false;// 默认没有权限
		for (int k = 0; k < userroles.size(); k++) {
			User_role ur = userroles.get(k);
			Role r = ur.getRole();
			int roleid = r.getRid();
			Role role = systemservice.getRolebyid(roleid);
			List<Role_permission> p = role.getRole_permission();
			for (int j = 0; j < p.size(); j++) {
				Role_permission rp = p.get(j);
				Permission permission = rp.getPermission();
				if (permission.getPermissionname().equals("总经理审批"))
					flag = true;
				else
					continue;
			}
		}
		if (flag == false)// 无权限
		{
			return grid;
		} else {
			int firstrow = (current - 1) * rowCount;
			List<SignApply> results = signService.getpageMantask(userid, firstrow, rowCount);
			int totalsize = signService.getallMantask(userid);
			List<SignTask> tasks = new ArrayList<SignTask>();
			for (SignApply apply : results) {
				SignTask task = new SignTask();
				task.setApply_time(apply.getApply_time());
				task.setUser_id(apply.getUser_id());
				task.setEnd_time(apply.getEnd_time());
				task.setId(apply.getId());
				task.setSign_type(apply.getSign_type());
				task.setProcess_instance_id(apply.getProcess_instance_id());
				task.setProcessdefid(apply.getTask().getProcessDefinitionId());
				task.setReason(apply.getReason());
				task.setStart_time(apply.getStart_time());
				task.setTaskcreatetime(apply.getTask().getCreateTime());
				task.setTaskid(apply.getTask().getId());
				task.setTaskname(apply.getTask().getName());
				tasks.add(task);
			}
			grid.setRowCount(rowCount);
			grid.setCurrent(current);
			grid.setTotal(totalsize);
			grid.setRows(tasks);
			return grid;
		}
	}
	@RequestMapping(value = "/dealsigntask", method = RequestMethod.POST)
	@ResponseBody
	public SignApply dealsigntask(@RequestParam("taskid") String taskid, HttpServletResponse response) {
		Task task = taskservice.createTaskQuery().taskId(taskid).singleResult();
		ProcessInstance process = runservice.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId())
				.singleResult();
		SignApply leave = signService.getleave(new Integer(process.getBusinessKey()));
		return leave;
	}
	/**
	 * 部门经理完成（会签）
	 * @param session
	 * @param taskid
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/managercomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public MSG managercomplete(HttpSession session, @PathVariable("taskid") String taskid, HttpServletRequest req) {
		String userid = (String) session.getAttribute("username");
//		Map<String, Object> variables = new HashMap<String, Object>();
//		String approve = req.getParameter("hrapprove");
//		variables.put("hrapprove", approve);
		// 获取流程实例
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid);
		return new MSG("success");
	}
	/**
	 * 总经理完成任务（会签）
	 * @param session
	 * @param total
	 * @param taskid
	 * @param req
	 * @return
	 */
	@RequestMapping(value="Managercomplete/{taskid}",method=RequestMethod.POST)
	@ResponseBody
	public MSG managercomplete(HttpSession session,@RequestParam("total")String total,@PathVariable("taskid") String taskid,HttpServletRequest req){
		String manager=req.getParameter("manager");
		String userid=(String) session.getAttribute("username");
//		Map<String,Object> variables=new HashMap<String,Object>();
//		variables.put("manager", manager);
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid);
		return new MSG("ok");
	}

}
